package com.web.servlet;

import com.alibaba.fastjson2.JSON;
import com.web.JDBCUtils;
import com.web.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author lenovo
 * @Description
 * @Date2025-2-27 21:27
 */



@WebServlet("/findStudentById")
public class FindStudentByIdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型为JSON
        resp.setContentType("application/json;charset=utf-8");

        // 从请求参数中获取学生ID
        String idStr = req.getParameter("id");

        // 检查学生ID是否为空
        if (idStr == null || idStr.trim().isEmpty()) {
            // 如果ID为空，返回错误信息
            resp.getWriter().write(JSON.toJSONString("error: Student ID is required"));
            return;
        }


        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            resp.getWriter().write(JSON.toJSONString("error: Invalid Student ID"));
            return;
        }


        String sql = "SELECT * FROM student_s WHERE id = ?";

        List<Student> students = JDBCUtils.query(Student.class, sql, id);
        if (students == null || students.isEmpty()) {

            resp.getWriter().write(JSON.toJSONString("error: Student not found"));
        } else {

            String jsonResult = JSON.toJSONString(students.get(0));
            // 将JSON数据写入响应流
            resp.getWriter().write(jsonResult);
        }
    }
}
